import { shallowRef } from 'vue'
import { cryptoEncryption } from '~/composables/crypto'

function mapToJson(data: Map<string, string>) {
  const json = {} as any
  data.forEach((value, key) => {
    json[key] = value
  })
  return json
}

function jsonToMap(json: Record<string, string>) {
  const map = new Map()
  Object.keys(json).forEach((key) => {
    map.set(key, json[key])
  })
  return map
}
export function useCachedUsers() {
  const cache = JSON.parse(localStorage.getItem('users') || '{}')
  const users = shallowRef(jsonToMap(cache))

  function updateCachedUsers(key: string, value: string) {
    users.value.set(key, cryptoEncryption(value))
    localStorage.setItem('sysinteg_users', JSON.stringify(mapToJson(users.value)))
  }

  return {
    users,
    updateCachedUsers,
  }
}
